import WebHeader from '@/www/components/WebHeader'
import WebFooter from '@/www/components/WebFooter'
import { getQuote, uploadFile, postQuoteOrder } from '@/apiv2/quote'
import yun from '@/utils/yun'

const CODE = 'DigitalSticker'

export default {
  components: { WebHeader, WebFooter },
  data() {
    return {
      quoteData: undefined,
      laminationDisable: undefined,
      checkValue: {
        flagLamination: false,//覆膜
        flagPressLine: false,//压线
        flagPlastic: false,//过塑
        flagFoldedPage: false,//折页
        flagCode: false,//打码
        flagPinholeLine: false,//针孔线
        flagPerforation: false,//打孔
        flagRound: false,//圆角
      },

      gramList: undefined,

      quoteValue: {
        category: undefined,
        gram: undefined,
        color: 'black',
        customQuantity: 1,
        style: 1,
        quantity: undefined,
        size: undefined,
        side: 1,
        customLength: undefined,
        customWidth: undefined,
        lamination: 'matteFilm',
        laminationSide: '1',
        foldedPage: undefined,
        pressLine: '1',
        pinholeLine: '1',
        angle: 'square',
        round: '1',
        perforation: '1',
        code: '1',
      },

      processSelectOptions: {

      },

      customSize:true,
      user: undefined,
      quote: undefined,
      quoteList: undefined,
      detail: undefined,
      fileList: [],
      postData: {
        quantity: undefined,
        detail: undefined,
        amount: undefined,
        fileIds: undefined
      },
      note: undefined
    }
  },

  created(){
    const user = JSON.parse(localStorage.getItem('user'))
    this.user = user

    getQuote(CODE).then(res => {
      let quoteData = res.config
      this.quoteValue.category = quoteData.cateData.list[0].name
      this.laminationDisable = !quoteData.cateData.list[0].canLamination
      this.quoteValue.gram = quoteData.cateData.list[0].gramList[0].gram
      this.gramList = quoteData.cateData.list[0].gramList
      this.quoteValue.size = quoteData.sizeData.list[0].name
      this.quoteData = quoteData
    })
  },

  methods: {

    onCategoryChange(){
      this.quoteData.cateData.list.forEach(item => {
        if(item.name == this.quoteValue.category){
          this.laminationDisable = item.canLamination
          if(!item.canLamination){
            this.checkValue.flagLamination = false
          }
          this.gramList = item.gramList
          this.quoteValue.gram = item.gramList[0].gram
        }
      })
    },

    getA3Price(category,color,gram,rate){
      let cateList = this.quoteData.cateData.list
      let price = 0
      cateList.forEach(item => {
        if(item.name == category){
          item.gramList.forEach(sitem => {
            if(gram == sitem.gram){
              price = parseFloat(item[color + 'Price']) * parseFloat(rate) + parseFloat(sitem.price)
            }
          })
          return price
        }
      })
      return price
    },



    getQuote(){
      let detail = ''

      let {customSize,quoteData,quoteValue,checkValue,postData} = this

      if(customSize && (!quoteValue.customLength || !quoteValue.customWidth)){
        this.$message.error('请输入自定义尺寸')
        return
      }
      let {length,width} = this.getFinalSize()

      const ADD_LENGTH = quoteValue.angle == 'square' ? 0 : 3

      const CUSTOM_SIZE = (length + ADD_LENGTH) + '*' + (width + ADD_LENGTH)

      const A3_SIZE = quoteData.param.sizeOfA3//拼版A3尺寸

      if(yun.ifPageAreaBiggerThan(CUSTOM_SIZE,A3_SIZE)){
        this.$message.error('自定义尺寸不能超过' + A3_SIZE)
        return
      }

      let a3AddFee = 0
      if(yun.ifPageAreaBiggerThan('90*54',CUSTOM_SIZE)){
        a3AddFee = parseFloat(quoteData.param.a3AddFee)
      }
      console.log('小尺寸加价='+a3AddFee)

      let finalQantity = parseInt(quoteValue.customQuantity) * parseInt(quoteValue.style)

      const COUNT_PER_PAGE = yun.getCountMakeupInSize(CUSTOM_SIZE,A3_SIZE)//单张拼版数量
      console.log('A3单张拼版数量='+COUNT_PER_PAGE)

      const A3_ADD_FEE = this.getA3AddFee(COUNT_PER_PAGE)
      console.log('A3加价=' + A3_ADD_FEE)

      const A3_PRICE = this.getA3Price(quoteValue.category,quoteValue.color,quoteValue.gram,quoteValue.side) + parseFloat(A3_ADD_FEE) + a3AddFee//A3价格
      console.log('A3单张价格='+A3_PRICE)

      const TOTAL_BASE_PAGE_COUNT = Math.ceil(finalQantity / COUNT_PER_PAGE)//总共需要纸张数量
      console.log('总共需要A3数量='+TOTAL_BASE_PAGE_COUNT)

      const PAPER_SIZE = yun.getPageSizeRange(CUSTOM_SIZE)//尺寸范围

      // console.log('单张价格：' + A3_PRICE)
      // console.log('单张拼版：' + COUNT_PER_PAGE)
      // console.log('需要纸张：' + TOTAL_BASE_PAGE_COUNT)
      // console.log('尺寸范围' + PAPER_SIZE.name)

      let materialAmount = A3_PRICE * parseFloat(TOTAL_BASE_PAGE_COUNT)

      detail += quoteValue.gram + quoteValue.category +'，'
        + '尺寸' + length + '*' + width +'，' + (quoteValue.color == 'black' ? '单黑' : (quoteValue.color == 'color' ? '彩色' : '满色底')) + '，'
        + (quoteValue.side == '1' ? '单面' : '双面') +'，'
        + finalQantity + quoteData.param.unit


      let discount = 1.0
      for(let i = 0; i < quoteData.quantityDiscountList.length; i++){
        let item = quoteData.quantityDiscountList[i]
        if(TOTAL_BASE_PAGE_COUNT >= parseFloat(item.start) && TOTAL_BASE_PAGE_COUNT <= parseFloat(item.end)){
          discount = parseFloat(item.discount)
          break
        }
      }

      let processAmount = 0

      if(checkValue.flagLamination){
        console.log('覆膜')
        console.log(parseFloat(quoteData.process.lamination) +'---'+ parseFloat(quoteValue.laminationSide) +'---'+ parseFloat(TOTAL_BASE_PAGE_COUNT))
        processAmount += parseFloat(quoteData.process.lamination) * parseFloat(quoteValue.laminationSide) * parseFloat(TOTAL_BASE_PAGE_COUNT)
      }

      let totalAmount = (materialAmount * discount + processAmount).toFixed(2)

      totalAmount = totalAmount < parseFloat(quoteData.param.minimumPrice) ? parseFloat(quoteData.param.minimumPrice) : totalAmount

      let quoteList = [{
        materialAmount: materialAmount.toFixed(2),
        quantity: finalQantity,
        processAmount: processAmount.toFixed(2),
        totalAmount: totalAmount
      }]

      let defaultFlag = false
      postData.amount = totalAmount
      postData.detail = detail
      this.postData = postData
      this.quoteList = quoteList
    },

    //获取A3加价
    getA3AddFee(count){
      let addFee = 0
      for(let i=0;i<this.quoteData.typesetQuantityAddFeeList.length;i++){
        let item = this.quoteData.typesetQuantityAddFeeList[i]
        if(count >= parseInt(item.start) && count <= parseInt(item.end)){
          addFee = parseFloat(item.addFee)
          break
        }
      }
      return addFee
    },

    //范围取值
    getQuantityRangeValue(list,quantity){
      let price = parseFloat(list[list.length - 1].price)
      for(let i=0;i<list.length;i++){
        let item = list[i]
        if(quantity >= parseInt(item.start) && quantity <= parseInt(item.end)){
          price = parseFloat(item.price)
          break
        }
      }
      return price
    },

    //尺寸范围取值
    getSizeRangeValue(list,size){
      let price = parseFloat(list[list.length-1].price)
      for(let i=0;i<list.length;i++){
        let item = list[i]
        if(!yun.ifPageAreaBiggerThan(size,item.size)){
          price = parseFloat(item.price)
          break
        }
      }
      return price
    },

    //匹配最终出纸尺寸和单张拼数
    matchSizePerCount(length,width){
      let sizeList = this.quoteData.sizeData.list

      //小于最小尺寸，按最小尺寸拼1个
      let minLong = parseInt(this.quoteData.param.minSize.split('*')[0])
      let minShort = parseInt(this.quoteData.param.minSize.split('*')[1])
      if(length <= minLong && width <= minShort){
        return {
          size: this.quoteData.sizeData.list[0],
          countPerPage: 1
        }
      }

      for(let i = 0; i < sizeList.length; i++){
        let sizeStr = sizeList[i].match(/\d+\*\d+/)[0]
        let l = parseInt(sizeStr.split('*')[0])
        let w = parseInt(sizeStr.split('*')[1])
        let {long,short} = this.findLongAndShort(l,w)
        if(length <= long && width <= short){
          return {
            size: sizeList[i],
            countPerPage: parseInt(long/length) * parseInt(short/width)
          }
        }
      }
      return undefined
    },

    //匹配数量阶梯
    matchStep(quantity){
      let returnQuantity = undefined
      let list = this.quoteData.stepData.list
      for(let i = 0; i < list.length; i++){
        if(quantity <= parseInt(list[i])){
          returnQuantity = parseInt(list[i])
          break
        }
      }
      return returnQuantity
    },

    //确认长边短边
    findLongAndShort(l,w){
      return {
        long: l >= w ? l : w,
        short: w <= l ? w : l
      }
    },

    //判断输入尺寸是否系小于或者等于指定尺寸
    checkIsLessOrEqualThanTargetSize(length,width,targetLength,targetWidth){
      let flag = false
      let long = undefined
      let short = undefined
      if(length >= width){
        long = length
        short = width
      }else{
        long = width
        short = length
      }

      if((long <= 420 && short <= 285) || (long <= 570 && short <= 210)){
        flag = true
      }

      return flag
    },


    //自定义尺寸切换
    onCustomSizeToggle(){
      this.quoteValue.customLength = undefined
      this.quoteValue.customWidth = undefined
    },

    selectQuantity(){
      if(this.quoteValue.quantity){
        this.quoteValue.customQuantity = undefined
      }
    },
    customQuantity(){
      if(this.quoteValue.customQuantity){
        this.quoteValue.quantity = undefined
      }else{
        this.quoteValue.quantity = this.quoteData.stepData.list[0]
      }
    },

    syncCheck(name,target){
      if(this.checkValue[name]){
        this.checkValue[target] = true
      }
    },

    offCheck(name,target){
      if(!this.checkValue[name]){
        this.checkValue[target] = false
      }
    },

    submitOrder(){
      const {fileList,postData} = this

      if(fileList.length < 1){
        this.$message.error('请上传设计稿')
        return
      }

      let fileIds = [];
      fileList.forEach(item => {
        fileIds.push(item.id)
      })
      postData.fileIds = fileIds

      const loading = this.$loading({
        lock: true,
        text: '正在创建订单',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      });

      postQuoteOrder(postData).then(res => {
        loading.close()
        this.$message.success('成功创建订单')
        this.$router.push({
          path: '/submitOrder',
          query: { id : res.id}
        })
      }).catch(err => {
        loading.close()
        this.$message.error('创建订单失败')
      })
    },

    handleUpload: async function(data){
      const formData = new FormData()
      formData.append('file', data.file)
      const res = await uploadFile(formData)
      let fileList = this.fileList
      fileList.push(res.file)
      this.fileList = fileList
      console.log(fileList)
    },

    //获取最终尺寸
    getFinalSize(){
      let {quoteValue,customSize} = this
      let length = undefined
      let width = undefined
      if(quoteValue.customLength && quoteValue.customWidth && customSize){
        length = parseInt(quoteValue.customLength)
        width = parseInt(quoteValue.customWidth)
      }else if(quoteValue.size){
        let sizeStr = quoteValue.size.match(/\d+\*\d+/)[0]
        length = parseInt(sizeStr.split('*')[0])
        width = parseInt(sizeStr.split('*')[1])
      }
      return {
        length: length,
        width: width
      }
    },

  }
}
